<?php
namespace App\Common\Lib\Com\Monitor;

use App\Common as com;
use App\Common\Lib\Com\Monitor as nameMonitor;

/**
 * Class Watch
 * @property nameMonitor\DataStore $dataStore
 */
class Watch extends com\Cla\ClaBase\CommonOfId\Client {

	/**
	 * 监听器id
	 * @var int|null
	 */
	private $watchId = null;

	/**
	 * 监听到的值
	 * @var mixed|null
	 */
	private $informValue = null;

	public function __construct( com\Cla\ClaBase\DataStore $dataStore, int $watchId ) {
		$this->watchId = $watchId;
		//
		parent::__construct( $dataStore );
	}

	/**
	 * 监听器id
	 * @return int
	 */
	public function getWatchId(  ):int {
		return $this->watchId;
	}

	/**
	 * 卸载监听器
	 * @return $this
	 */
	public function unWatch(  ):self {
		$this->dataStore->main->unWatchOfId( $this->getWatchId() );
		//
		return $this;
	}

	/**
	 * 广播值
	 * @param $value
	 */
	public function inform( $value ) {
		$this->informValue = $value;
	}

	/**
	 * 获取值，如果值为null则抛出异常
	 * @return mixed
	 * @throws
	 */
	public function getOrFail() {
		if( $this->informValue === null ){
			throw com\Lib\Err\Exception::makeOfNew( 'watch值不存在', com\Lib\Err\Code::$sysDataNotExist );
		}
		return $this->informValue;
	}

	/**
	 * 获取值并卸载监听器，如果值为null则抛出异常
	 * @return mixed
	 * @throws
	 */
	public function getAndUnWatchOrFail() {
		if( $this->informValue === null ){
			throw com\Lib\Err\Exception::makeOfNew( 'watch值不存在', com\Lib\Err\Code::$sysDataNotExist );
		}
		//
		$this->unWatch();
		//
		return $this->informValue;
	}
	
}
